package MainPage;
import java.awt.*;
import javax.sound.sampled.*;
import javax.swing.*;
import javax.xml.transform.Result;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.sql.*;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

public class userMainPage extends JFrame implements ActionListener,MouseListener
{
    static JButton button3,button4;  
    JPasswordField passwordField;
    JTextField username;
    JPanel logonPanel;
    JLabel display;
    displayBackground topChoicePanel;
    int X1=250,Y1=120,degree1=45,widthOfOSI,heightOfOSI,x=200,bounce=0;
    int Xshadow=450,Yshadow=120,ovalX=150,ovalY=650;
    int colorIndex=0;
	Image calender,OSI,backgroundPicture,patternPicture,imageCursor;
	AffineTransform affineTransform;
	boolean up=false,down=true,resetImage=false,accountexist=true;
	static boolean stopPlayback = false;;
	Container container;
	Timer timer,welcomePanel,logonTimer;
	String message="Welcome to MyOrganizer!!",SQL,Password;
	char[] checkPassword,basePassword;
	int messagePosition = -1,messageHeight,messageWidth,charWidth;
	float hue;
	public static Toolkit tk; 
	public static Dimension screensize;
	static Connection con;
	static String user_name,user_password;
	static ResultSet rs;
	static Statement stmt;
	static JLabel register;
	static SourceDataLine songSource;
    static AudioFormat songFormat;
    static AudioInputStream song;
    static int userCode;
	
    
	public userMainPage()
      {
    	  loadComponent();
    	  loadmain();
    	  timer=new Timer(9,new time());
    	  timer.start();
    	  welcomePanel=new Timer(200,new movePanetime());
    	  welcomePanel.start();
    	  logonTimer=new Timer(200,new logon());
    	  logonTimer.start();
    	  getCon();
    	  createstatement();
      }
      
      public static void main(String[] args) 
  	 {
  	    initialGUI();
 	    button3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
 	    button4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
 	    register.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
     }
      public static void initialGUI()
      {
    	 userMainPage frame=new userMainPage();
    	 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	 frame.setResizable(false);
         frame.setLocationRelativeTo(null);
    	 tk= Toolkit.getDefaultToolkit();
    	 screensize = tk. getScreenSize ();
 	     
    	 frame.setSize(screensize.width,screensize.height);
 	     frame.setTitle("My Organizer");
 	     frame.setVisible(true);
    	  
      }
      public Connection getCon()
      {
         try {
             DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
             con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "hr", "hr");
             System.out.println("connection established");
         }
         catch (Exception e) {
             System.err.println("connection error!!!");
         }
         return con;
     }
      private void createstatement()
      {
          try
          {
             stmt = con.createStatement();
          }
          catch (SQLException ex)
          {
             Logger.getLogger(userMainPage.class.getName()).log(Level.SEVERE, null, ex);
          }
      }

	public void loadComponent() 
      { 
    	 
    	//  tk= Toolkit.getDefaultToolkit();
    	  loadImage();
    	//  c = tk.createCustomCursor(imageCursor, new Point(0,0),"cursorName");
    	
    	  container=getContentPane();
    	  
    	  topChoicePanel=new displayBackground();
    	  topChoicePanel.setLayout(null);
		  topChoicePanel.addMouseListener(this);
    	  container.add(topChoicePanel);
    	  
    	  
    	  
    	  display = new JLabel() 
    	  {
              public void paintComponent(Graphics g) 
              {
                 super.paintComponent(g);
                 g.setColor(Color.getHSBColor(hue,1,1));
                 g.drawString(message, getWidth() - messagePosition, 
                                       getHeight()/2 + messageHeight/2);
              }
           };
           Font messageFont = new Font("Monospaced", Font.BOLD, 30);
           display.setFont(messageFont);
           
           FontMetrics fm = getFontMetrics(messageFont);
           messageWidth = fm.stringWidth(message);
           messageHeight = fm.getAscent();
           charWidth = fm.charWidth('H');
           topChoicePanel.add(display).setBounds(300,10,800,35);
    	  
      }
      public void loadmain()
      {
    	  button3=new JButton("Login");
    	  button3.addActionListener(this);
    	  button4=new JButton("Cancel");
    	  button4.addActionListener(this);
    	  register=new JLabel("Register");
    	  register.setForeground(Color.white);

    	  username=new JTextField(20);
    	  passwordField = new JPasswordField(10);
    	  passwordField.addActionListener(this);

    	  //button3.setBackground(Color.cyan);
    	  //button3.setForeground(Color.red);
    	  //button4.setBackground(Color.cyan);
    	  //button3.setForeground(Color.red);
    	  
    	  button3.setBackground(Color.getHSBColor(0.5529412F,0.21960784F,0.36078432F));
    	  button3.setForeground(Color.getHSBColor(0.10196078F,0.75686276F,0.9372549F));
    	  button4.setBackground(Color.getHSBColor(0.5529412F,0.21960784F,0.36078432F));
    	  button4.setForeground(Color.getHSBColor(0.10196078F,0.75686276F,0.9372549F));
    	  
    	  register.addMouseListener(new java.awt.event.MouseAdapter() {
        	  public void mouseClicked(java.awt.event.MouseEvent evt) {
        	  registerMouseClicked(evt);
        	  }
        	  public void mouseEntered(java.awt.event.MouseEvent evt){
        	  registerMouseEntered(evt);	  
        	  }
        	  public void mouseExited(java.awt.event.MouseEvent evt){
        	  registerMouseExited(evt);	  
        	  }
        	  });
    	  
    	  //topChoicePanel.add(button3).setBounds(840,425,100,30);
    	  //topChoicePanel.add(button4).setBounds(950,425,110,30);
    	  //topChoicePanel.add(username).setBounds(840,350,200,20);
	      //topChoicePanel.add(passwordField).setBounds(840,395,200,20);
	      //topChoicePanel.add(register).setBounds(866,455,100,30);
	      topChoicePanel.add(button3).setBounds(610,435,90,30);
    	  topChoicePanel.add(button4).setBounds(720,435,90,30);
    	  topChoicePanel.add(username).setBounds(610,360,200,20);
	      topChoicePanel.add(passwordField).setBounds(610,405,200,20);
	      topChoicePanel.add(register).setBounds(630,465,100,30);
	      topChoicePanel.revalidate();
    	  
      }
      public void loadImage()
      {
    	  ImageIcon icon3=new ImageIcon(getClass().getResource("/resource/calenderImage.jpg"));
    	  calender=icon3.getImage();
         
    	  ImageIcon background=new ImageIcon(getClass().getResource("/resource/calendarBackground.png"));
    	  backgroundPicture=background.getImage();
      }

      private void registerMouseClicked(java.awt.event.MouseEvent evt) 
      {
    	  firstPage.playAudio2(getClass().getResource("/resource/buttonHit.wav").getFile());
    	  
    	  register.setForeground(Color.red);
    	  performRegister();
      }
      private void registerMouseEntered(java.awt.event.MouseEvent evt)
      {
    	  //register.setForeground(Color.yellow);
    	  register.setForeground(Color.getHSBColor(0.10196078F,0.75686276F,0.9372549F));
      }
      private void registerMouseExited(java.awt.event.MouseEvent evt)
      {
    	  register.setForeground(Color.white);
      }
      class displayBackground extends JPanel
      {
    	  
    	  public void paintComponent (Graphics g)
    	  {
    		  
    		  this.setSize(1300,750);
    		  checkOSI();
    		  super.paintComponent(g);
    		  Graphics2D g2d = (Graphics2D)g;
    		
    		  //g2d.setColor(Color.getHSBColor(0.141176F, 0.0F, 0.29411F));
    		  //g2d.fillRect(0, 0, getWidth(), getHeight());
    		  //g2d.setColor(Color.red);
    		  //g2d.fillRect(5, 5, getWidth()-10, getHeight()-10);
    		  g2d.drawImage(backgroundPicture,0, 0, getWidth(), getHeight(),this);
    		
    		  g2d.drawImage(patternPicture,10, 10, getWidth()-20, 35,this);
    		  g2d.setColor(Color.getHSBColor(0.09411765F, 0.83137256F, 0.9490196F));
    		  g2d.fillOval(ovalX,ovalY,Xshadow,Yshadow);
    		  g2d.setColor(Color.white);
    		  Font messageFont1 = new Font("Monospaced", Font.BOLD, 20);
              g2d.setFont(messageFont1);
             
    		  g2d.drawString("UserName : ",getWidth()*6/16,getHeight()/2);
    		  g2d.drawString("Password :",getWidth()*6/16 , getHeight()/2+45);

    		  affineTransform = new AffineTransform();
    		  affineTransform.setToTranslation(X1,Y1);
    		  affineTransform.rotate(Math.toRadians(degree1),X1/2,Y1/2);
    		  
    		  g2d.drawImage(calender, affineTransform, this); 

    	  }
      }
      
      private void checkOSI() 
      {
         if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) 
         {
            OSI = null;  
            OSI = createImage(getSize().width, getSize().height);
            widthOfOSI = getSize().width;
            heightOfOSI = getSize().height;
            Graphics OSG = OSI.getGraphics();  
            OSG.setColor(getBackground());
            OSG.fillRect(0, 0, widthOfOSI, heightOfOSI);
            OSG.dispose();
         }
      }
      public void ImageControler()
      {
    	  if (resetImage)
    	  {
    		  X1=250;
    		  Y1=120;
    		  degree1=45;
    		  resetImage=false;
    		  down=true;
    		  bounce=0;
    		  x=200;
    		  Xshadow=450;
    		  Yshadow=120;
    		  ovalX=150;
    		  ovalY=650;
    	  }
    	  else
    	  {
    	  if (down)
 		 {
 		  Y1++;
 		  Xshadow--;
 		  if (Xshadow%3== 0)
 		  {
 			  Yshadow--;
 			   ovalX++;
 		  }
 		  if (Y1%3== 0)
 			 X1--;
 		  
 		  if (Y1>400)
 		 {
 			 down=false;
 			 bounce+=1;
 			 
 		 }
 		 if (bounce==1)
				 degree1=67;
			 else if (bounce==2)
			 { 
				 degree1=90;
			 }
 		 }
 		 else 
 		 {
 			 Y1--;
 			 Xshadow++;
 			 if (Xshadow%3== 0)
 			 {
 				 Yshadow++;
 				 ovalX=(int) (ovalX-2.5);
 			 }
 			 if (ovalX%7==0)
 				 ovalY++;
 			 if (x==300)
 			 {
 				Y1=395;
 				Yshadow=0;
 				Xshadow=0;
 				timer.stop();
 			    timer.setInitialDelay(1000);
 				timer.start();
                 
 				resetImage=true;
 			 }
 			 if (Y1<x)
 			 {
 				 down=true;
 				 x=x+50;
 			 }
 		 }
      }}
    

      private class time implements ActionListener
      {
    	  public void actionPerformed(ActionEvent evt) 
          {
    		  ImageControler();
    		  repaint();
          }
      }
      private class logon implements ActionListener
      {
    	  public void actionPerformed(ActionEvent evt) 
          {
    		  colorIndex++; 
              if (colorIndex > 100)
                 colorIndex = 0;
               hue = colorIndex / 100.0F; 
    		  repaint();
          }
      }
      private class movePanetime implements ActionListener
      {
    	  
    	  public void actionPerformed(ActionEvent evt) 
          {
    		  messagePosition += charWidth;
    	       if (getSize().width - messagePosition + messageWidth < 400) 
    	       {
    	          messagePosition = 0;
    	       }
    		  repaint();
          }
      }

	@Override
	public void actionPerformed(ActionEvent evt) 
	{
		String command = evt.getActionCommand();
		checkOSI();
		
		if (command.equals("Cancel"))
		{
			firstPage.playAudio(getClass().getResource("/resource/buttonHit.wav").getFile());
			username.setText("");
            passwordField.setText("");
		}
		
		if (command.equals("Login"))
		{
			firstPage.playAudio(getClass().getResource("/resource/buttonHit.wav").getFile());
			checkPassword=passwordField.getPassword();
			SQL="SELECT USER_PASSWORD FROM USER_DETAIL WHERE USER_USERNAME='"+username.getText()+"'";
			try {
				rs=stmt.executeQuery(SQL);
				rs.next();
				Password=rs.getString(1);
				accountexist=true;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this,
		                "Account is not existed! Please register a new account.",
		                "Error Message",
		                JOptionPane.ERROR_MESSAGE);
            username.setText("");
            passwordField.setText("");
            accountexist=false;
            
			}
			if (accountexist)
			{
			basePassword=new char[Password.length()];
			for(int a=0;a<Password.length();a++)
			{
				basePassword[a]=Password.charAt(a);	
			}
			
				if (isPasswordCorrect(checkPassword,basePassword))
				{
					SQL="SELECT USER_CODE FROM USER_DETAIL WHERE USER_USERNAME='"+username.getText()+"'";
					try {
						rs=stmt.executeQuery(SQL);
						rs.next();
						userCode=rs.getInt(1);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(userCode);
					user_name=username.getText();
					user_password=Password;
					performMainPage();
				}
			
			else
			{
				JOptionPane.showMessageDialog(this,
		                "Invalid password. Try again.",
		                "Error Message",
		                JOptionPane.ERROR_MESSAGE);
            username.setText("");
            passwordField.setText("");
			}
			}
		}
		repaint();
	}
    
	private static boolean isPasswordCorrect(char[] input,char[] correctPassword) 
	{
	    boolean isCorrect = true;

	    if (input.length != correctPassword.length)
	    {
	        isCorrect = false;
	    } 
	    else 
	    {
	        isCorrect = Arrays.equals (input, correctPassword);
	    }

	    //Zero out the password.
	    Arrays.fill(correctPassword,'0');

	    return isCorrect;
	}
	
	void performRegister()
	{
		registration register_page=new registration()
		{
			public String getParameter(String name)
			{
		           if (name.equalsIgnoreCase("msg"))
		           {
		              return "Local Frame";
		           }
		           return null;
		    }
		};
		register_page.setSize(screensize.width,screensize.height);
		this.dispose();
		register_page.setVisible(true);
		
	}

	void performMainPage()
	{
		//pane.removeAll();
		firstPage first_page=new firstPage()
		{
			public String getParameter(String name)
			{
		           if (name.equalsIgnoreCase("msg"))
		           {
		              return "Local Frame";
		           }
		           return null;
		    }
		};
		first_page.setSize(screensize.width,screensize.height);
		//this.setVisible(false);
		this.setVisible(false);
		first_page.setVisible(true);
		
	}
	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent e) 
	{
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
      
}
